#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/delay.h>

#include "packet.h"

volatile unsigned char lastbyte = 0;
volatile unsigned char gotbyte = 0;

volatile unsigned char sentbyte = 0;

ISR(USART0_RX_vect)
{
	char c = UDR0;
	
	if(bit_is_clear(UCSR0A, FE))
	{
		lastbyte = c;
		gotbyte = 1;
	}
}

ISR(USART0_TX_vect)
{
	sentbyte = 1;
}

void sendchar(unsigned char c)
{
	sentbyte = 0;
	UDR0 = c;
	while(sentbyte == 0);
}

void calcchksum(packet* cmd)
{
	unsigned char c = 0;
	
	for(int i = 0; i<sizeof(packet); i++)
		c += cmd->packet[i];
	
	cmd->chksum = 255-c;
}

void transmitpacket(packet cmd)
{
	calcchksum(&cmd);
	
	for(int i = 0; i<sizeof(packet); i++)
		sendchar(cmd.packet[i]);
}

unsigned char receivepacket(void)
{
	for(int i = 0; i<10; i++)
	{
		if(gotbyte)
			return lastbyte;
		
		_delay_ms(20);
	}
	
	return 0;
}
